from datetime import datetime, timedelta
from typing import Optional
import hashlib
import secrets
import logging

from app.storage.json_storage import storage
from app.models.schemas import UserCreate, UserLogin, UserInfo
from app.config import settings

logger = logging.getLogger(__name__)

class SimpleJSONAuthService:
    """简化的JSON文件认证服务 - 只包含基本功能"""
    
    def __init__(self):
        self.secret_key = settings.SECRET_KEY
    
    def hash_password(self, password: str) -> str:
        """简单的密码哈希 - 使用SHA256 + salt"""
        salt = secrets.token_hex(16)
        password_hash = hashlib.sha256((password + salt + self.secret_key).encode()).hexdigest()
        return f"{salt}:{password_hash}"
    
    def verify_password(self, password: str, hashed_password: str) -> bool:
        """验证密码"""
        try:
            salt, stored_hash = hashed_password.split(':')
            password_hash = hashlib.sha256((password + salt + self.secret_key).encode()).hexdigest()
            return password_hash == stored_hash
        except:
            return False
    
    def create_simple_token(self, user_id: str, username: str) -> str:
        """创建简单的令牌 - 不使用JWT，只是简单的编码"""
        timestamp = int(datetime.utcnow().timestamp())
        expire_time = timestamp + (settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60)
        
        # 简单的令牌格式: user_id:username:expire_time:signature
        data = f"{user_id}:{username}:{expire_time}"
        signature = hashlib.sha256((data + self.secret_key).encode()).hexdigest()[:16]
        token = f"{data}:{signature}"
        
        # Base64编码使其看起来像真正的令牌
        import base64
        return base64.b64encode(token.encode()).decode()
    
    def verify_token(self, token: str) -> Optional[dict]:
        """验证令牌"""
        try:
            import base64
            decoded = base64.b64decode(token.encode()).decode()
            parts = decoded.split(':')
            
            if len(parts) != 4:
                return None
            
            user_id, username, expire_time, signature = parts
            
            # 验证签名
            data = f"{user_id}:{username}:{expire_time}"
            expected_signature = hashlib.sha256((data + self.secret_key).encode()).hexdigest()[:16]
            
            if signature != expected_signature:
                return None
            
            # 检查是否过期
            if int(expire_time) < int(datetime.utcnow().timestamp()):
                return None
            
            return {
                "user_id": user_id,
                "username": username,
                "expire_time": int(expire_time)
            }
        except:
            return None
    
    def register(self, user_data: UserCreate) -> Optional[UserInfo]:
        """用户注册 - 简化版本"""
        try:
            # 检查用户名是否已存在
            existing_user = storage.get_user_by_username(user_data.username)
            if existing_user:
                raise ValueError("用户名已存在")

            # 检查邮箱是否已存在（简化版本：遍历所有用户）
            all_users = storage.get_users()
            for user in all_users:
                if user.get('email') == user_data.email:
                    raise ValueError("邮箱已被使用")
            
            # 创建用户
            user_dict = {
                'username': user_data.username,
                'email': user_data.email,
                'hashed_password': self.hash_password(user_data.password),
                'full_name': getattr(user_data, 'full_name', None),
                'role': 'user',
                'is_active': True
            }
            
            new_user = storage.create_user(user_dict)
            logger.info(f"User registered: {user_data.username}")
            
            return UserInfo(
                id=new_user['id'],
                username=new_user['username'],
                email=new_user['email'],
                full_name=new_user.get('full_name'),
                role=new_user['role'],
                is_active=new_user['is_active'],
                created_at=datetime.fromisoformat(new_user['created_at']),
                last_login=None
            )
            
        except Exception as e:
            logger.error(f"Registration error: {e}")
            raise
    
    def login(self, login_data: UserLogin) -> Optional[dict]:
        """用户登录 - 简化版本，返回简单的令牌信息"""
        try:
            # 获取用户
            user = storage.get_user_by_username(login_data.username)
            if not user:
                return None
            
            # 验证密码
            if not self.verify_password(login_data.password, user['hashed_password']):
                return None
            
            # 检查用户是否激活
            if not user.get('is_active', True):
                return None
            
            # 更新最后登录时间
            storage.update_user(user['id'], {
                'last_login': datetime.utcnow().isoformat()
            })
            
            # 创建令牌
            token = self.create_simple_token(user['id'], user['username'])
            
            # 存储会话（简化版本）
            storage.set_session(
                f"session:{user['id']}", 
                {
                    'user_id': user['id'],
                    'username': user['username'],
                    'login_time': datetime.utcnow().isoformat()
                },
                expire_seconds=settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60
            )
            
            logger.info(f"User logged in: {user['username']}")
            
            return {
                "token": token,
                "token_type": "bearer",
                "expires_in": settings.ACCESS_TOKEN_EXPIRE_MINUTES * 60,
                "user": {
                    "id": user['id'],
                    "username": user['username'],
                    "email": user['email'],
                    "role": user['role']
                }
            }
            
        except Exception as e:
            logger.error(f"Login error: {e}")
            return None
    
    def get_current_user(self, token: str) -> Optional[dict]:
        """根据令牌获取当前用户"""
        try:
            # 验证令牌
            token_data = self.verify_token(token)
            if not token_data:
                return None
            
            # 获取用户信息
            user = storage.get_user_by_id(token_data['user_id'])
            if not user or not user.get('is_active', True):
                return None
            
            return user
            
        except Exception as e:
            logger.error(f"Get current user error: {e}")
            return None
    
    def logout(self, user_id: str) -> bool:
        """用户登出"""
        try:
            # 删除会话
            storage.delete_session(f"session:{user_id}")
            logger.info(f"User logged out: {user_id}")
            return True
        except Exception as e:
            logger.error(f"Logout error: {e}")
            return False
